import { z } from "zod";
import axios from 'axios'
import { RequestHandler } from "express";
import { SsoToken, useEntityManager } from "./entities";

const handler: RequestHandler = async (req, res, next) => {
    const input = z.object({
        code: z.string(),
        state: z.string(),
    })
    const body = input.parse(req.query)
    const authHost = process.env.AUTH_HOST
    const authAppId = process.env.AUTH_APPID
    const authAppSecret = process.env.AUTH_SECRET
    const siteHost = process.env.SITE_HOST
    const redirect_uri = `https://www.jointmodeling.cn/sso/token`
    const url = `${authHost}/oauth/token?grant_type=authorization_code&code=${body.code}&client_id=${authAppId}&client_secret=${authAppSecret}&redirect_uri=${redirect_uri}`
    const result = await axios.get(url).then(res => res.data).catch(e => console.error(e))
    // 拿到access_token
    await useEntityManager(async m => {
        const token = m.create(SsoToken, {
            access_token: result.access_token,
            token_type: result.token_type,
            refresh_token: result.refresh_token,
            expires_in: Date.now() + result.expires_in * 1000,
            scope: result.scope,
            openid: result.openid,
            domain: result.domain
        })
        await m.save(token)
    });
    res.redirect(`${siteHost}/${body.state}?access_token=${result?.access_token}`);
}
export default handler;